package com.haidechizi.i18n.code.generator.common.message.translate;


import com.haidechizi.i18n.code.generator.common.GlobalConfig;
import com.haidechizi.i18n.code.generator.common.message.constants.TranslateTypeConstants;
import com.haidechizi.i18n.code.generator.common.message.translate.cache.TranslateCacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class ProxyTranslate extends AbstractTranslate {

    @Autowired
    private TranslateCacheService translateCacheService;


    /**
     * 类型
     *
     * @return
     */
    @Override
    public String type() {
        return TranslateTypeConstants.PROXY;
    }

    /**
     * 翻译顶层接口
     *
     * @param data
     * @param language
     * @return
     */
    @Override
    public String translate(String data, String currentLanguage, String language) {
        // 检测是否命中缓存
        String cache = translateCacheService.getCache(currentLanguage, language, data);
        if (StringUtils.isNotBlank(cache)) {
            return cache;
        }
        String translateType = GlobalConfig.getTranslateType();
        if (StringUtils.isBlank(translateType)) {
            translateType = TranslateTypeConstants.DEFAULT;
        }
        String translateData = AbstractTranslate.getInstance(translateType).translate(data, currentLanguage, language);
        if (StringUtils.isNotBlank(translateData)) {
            // 写入缓存
            translateCacheService.addCache(currentLanguage, language, data, translateData);
        }

        return StringUtils.isBlank(translateData) ? data : translateData;
    }
}
